/// <reference path="jquery-1.10.1.min.js" />
/// <reference path="ProtoClass.js" />
/// <reference path="jquery-ui-1.10.3.custom.min.js" />

var localStorageControl = (function () {
    var initial = 0;
    var max = -1;
    var current = 0;

    function clickPrevious() {
        if (max == -1) {
            return;
        }

        current = current - 1;
        if (current < initial) {
            current = max;
        }
        
        var objectToRetrieve = localStorage.getItem(current);
        $("#container-selected").html(objectToRetrieve);
    }

    function clickNext() {
        if (max == -1) {
            return;
        }

        current = current + 1;
        if (current > max) {
            current = initial;
        }

        var objectToRetrieve = localStorage.getItem(current);
        $("#container-selected").first().html(objectToRetrieve);
    }

    function addElement() {
        var objectToStore = $("#container-selected").first().html();
        max = max + 1;
        localStorage.setItem(max, objectToStore);
        current = max;
    }

    return {
        previous: clickPrevious,
        next: clickNext,
        add: addElement
    }
}());

var Worker = Class.create({
    initialize: function (firstName, lastName, age, workExperience) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.workExperience = workExperience;
    },

    fullName: function () {
        return this.firstName + " " + this.lastName;
    },

    renderPartial: function () {
        var container = $("<div>" + this.fullName() + "</div>");
        container.addClass("worker");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        return container;
    },

    renderFull: function () {
        var container = $("<div></div>");
        container.addClass("worker-full");
        var nameVisual = $("<div>" + this.fullName() + "</div>");
        nameVisual.addClass("name-visualisation");
        container.append(nameVisual);
        var characteristics = $("<div> Age:" + this.age + ", work experience: " + this.workExperience + "</div>");
        characteristics.addClass("characteristics-visualisation");
        container.append(characteristics);

        return container;
    }
});

var Expert = Class.create(Worker, {
    initialize: function ($super, firstName, lastName, age, workExperience, degree) {
        $super(firstName, lastName, age, workExperience);
        this.degree = degree;
    },

    renderPartial: function ($super) {
        var container = $super();
        container.addClass("expert");

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("expert-full");
        var degree = $("<div> Degree:" + this.degree + "</div>");
        degree.addClass("degree-visualisation");
        container.append(degree);

        return container;
    }
});

var Manager = Class.create(Expert, {
    initialize: function ($super, firstName, lastName, age, workExperience, degree) {
        $super(firstName, lastName, age, workExperience, degree);
        this.workers = [];
    },

    addManagedEmployee: function (employee) {
        if (employee instanceof Manager) {
            throw new Error("Managers cannot manage other managers.");
        }

        this.workers.push(employee);
    },

    renderPartial: function ($super) {
        var container = $super();
        container.addClass("manager");

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("manager-full");
        var managedPeople = $("<div> Number of managed employees: " + this.workers.length + "</div>");
        container.append(managedPeople);

        return container;
    }
});

var Building = Class.create({
    initialize: function (name, area, retailPrice, rented, yearlyRent) {
        this.name = name;
        this.area = area;
        this.retailPrice = retailPrice;
        this.rented = rented;
        if (this.rented) {
            this.yearlyRent = yearlyRent;
        }
        else {
            this.yearlyRent = "N/a";
        }
    },

    renderPartial: function () {
        var container = $("<div></div>");
        container.addClass("building");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        var buildingName = $("<div>Building name: " + this.name + "</div>");
        buildingName.addClass("buildingName");

        container.append(buildingName);

        this.container = container;
        return container;
    },

    renderFull: function () {
        var container = $("<div></div>");
        container.addClass("building-full");

        var buildingName = $("<div>Building name: " + this.name + "</div>");
        buildingName.addClass("building-name");
        container.append(buildingName);

        var areaOfBuilding = $("<div>Area of building: " + this.name + " square meters.</div>");
        container.append(areaOfBuilding);

        var retailPriceOfBuilding = $("<div>Retail price:" + this.name + " leva</div>");
        container.append(retailPriceOfBuilding);

        var rentedBuilding;
        if (!this.rented){
            rentedBuilding = $("<div>Building owned</div>");
        }
        else{
            rentedBuilding = $("<div>Building rented for " + this.yearlyRent + " leva per year.</div>");
        }

        container.append(rentedBuilding);

        this.fullContainer = container;
        return container;
    }
});

var AdministrativeBuilding = Class.create(Building, {
    initialize: function ($super, name, area, retailPrice, rented, yearlyRent) {
        $super(name, area, retailPrice, rented, yearlyRent);
        this.workers = [];
    },

    addWorker: function (employee) {
        if (!(employee instanceof Worker)) {
            throw new Error("Only workers can populate buildings.");
        }

        this.workers.push(employee);
        if (this.container) {
            if (this.container.children("ul.list-of-workers").length > 0) {
                $(this.container).children("ul.list-of-workers").first().append(employee.renderPartial());
            }
            else {
                var workersList = $("<ul></ul>");
                workersList.addClass("list-of-workers");
                for (var i = 0, len = this.workers.length; i < len; i++) {
                    var listItem = this.workers[i].renderPartial();
                    workersList.append(listItem);
                }

                workersList.sortable();
                if (this.container.children("ul.list-of-machines").length > 0) {
                    var collection = $(this.container).children(".buildingName");
                    collection.after(workersList);
                }
                else {
                    $(this.container).append(workersList);
                }
            }
        }

        if (this.fullContainer) {
            if ($(this.fullContainer).parent().length > 0) {
                $(this.fullContainer).children(".number-container-workers").first().html("Number of employees in building: " + this.workers.length);
            }
        }
    },

    renderPartial: function ($super) {
        var container = $super();
        container.addClass("administrative");

        if (this.workers.length > 0) {
            var workersList = $("<ul></ul>");
            workersList.addClass("list-of-workers");
            for (var i = 0, len = this.workers.length; i < len; i++) {
                var listItem = this.workers[i].renderPartial();
                workersList.append(listItem);
            }

            workersList.sortable();
            container.append(workersList);
        }

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("administrative-full");

        var managedPeople = $("<div>Number of employees in building: " + this.workers.length + "</div>");
        managedPeople.addClass("number-container-workers");
        container.append(managedPeople);
        container.sortable();

        return container;
    }
});

var ProductionBuilding = Class.create(AdministrativeBuilding, {
    initialize: function ($super, name, area, retailPrice, rented, yearlyRent) {
        $super(name, area, retailPrice, rented, yearlyRent);
        this.machines = [];
        this.vehicles = [];
    },

    addMachine: function (machine) {
        if (!(machine instanceof Machine)) {
            throw new Error("We need machines to work.");
        }

        this.machines.push(machine);
        if (this.container) {
            if (this.container.children("ul.list-of-machines").length > 0) {
                $(this.container).children("ul.list-of-machines").first().append(machine.renderPartial());
            }
            else {
                var machinesList = $("<ul></ul>");
                machinesList.addClass("list-of-machines");
                for (var i = 0, len = this.machines.length; i < len; i++) {
                    var listItem = this.machines[i].renderPartial();
                    machinesList.append(listItem);
                }

                machinesList.sortable();
                $(this.container).append(machinesList);
            }
        }

        if (this.fullContainer) {
            if ($(this.fullContainer).parent().length > 0) {
                $(this.fullContainer).children(".number-container-machines").first().html("Number of machines in building: " + this.machines.length);
            }
        }
    },

    addVehicle: function (vehicle) {
        if (!(vehicle instanceof Vehicle)) {
            throw new Error("We need vehicles to work and travel.");
        }

        this.vehicle.push(vehicle);
        if (this.container) {
            if (this.container.children("ul.list-of-machines").length > 0) {
                $(this.container).children("ul.list-of-vehicles").first().append(vehicle.renderPartial());
            }
            else {
                var vehiclesList = $("<ul></ul>");
                vehiclesList.addClass("list-of-vehicles");
                for (var i = 0, len = this.vehicles.length; i < len; i++) {
                    var listItem = this.vehicles[i].renderPartial();
                    vehiclesList.append(listItem);
                }

                vehiclesList.sortable();
                $(this.container).append(vehiclesList);
            }
        }

        if (this.fullContainer) {
            if ($(this.fullContainer).parent().length > 0) {
                $(this.fullContainer).children(".number-container-vehicles").first().html("Number of vehicles in production building: " + this.vehicles.length);
            }
        }
    },

    renderPartial: function ($super) {
        var container = $super();
        container.addClass("production");

        if (this.machines.length > 0) {
            var machinesList = $("<ul></ul>");
            machinesList.addClass("list-of-machines");
            for (var i = 0, len = this.machines.length; i < len; i++) {
                var listItem = this.machines[i].renderPartial();
                machinesList.append(listItem);
            }

            machinesList.sortable();
            container.append(machinesList);
        }

        if (this.vehicles.length > 0) {
            var vehiclesList = $("<ul></ul>");
            vehiclesList.addClass("list-of-vehicles");
            for (var i = 0, len = this.vehicles.length; i < len; i++) {
                var listItem = this.vehicles[i].renderPartial();
                vehiclesList.append(listItem);
            }

            vehiclesList.sortable();
            container.append(vehiclesList);
        }

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("production-full");

        var managedMachines = $("<div>Number of machines in building: " + this.machines.length + "</div>");
        managedMachines.addClass("number-container-machines");
        container.append(managedMachines);
        container.sortable();

        var managedVehicles = $("<div>Number of vehicles in building: " + this.vehicles.length + "</div>");
        managedVehicles.addClass("number-container-vehicles");
        container.append(managedVehicles);
        container.sortable();

        return container;
    }
});

var Machine = Class.create({
    initialize: function (years, guarantee, amortizationPeriod) {
        this.name = "Production machine";
        this.yearsOld = years;
        this.guarantee = guarantee;
        this.amortizationPeriod = amortizationPeriod;
    },

    renderPartial: function () {
        var container = $("<div>" + this.name + "</div>");
        container.addClass("machine");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        return container;
    },

    renderFull: function () {
        var container = $("<li></li>");
        container.addClass("machine-full");

        var nameVisual = $("<div>" + this.name + "</div>");
        nameVisual.addClass("name-visualisation");
        container.append(nameVisual);
        
        var ageVisual = $("<div>Purchased before" + this.yearsOld + " years</div>");
        ageVisual.addClass("age-visualisation");
        container.append(ageVisual);

        var guaranteeVisual = $("<div>Guarantee left: " + (this.guarantee - this.yearsOld) + " years</div>");
        guaranteeVisual.addClass("guarantee-visualisation");
        container.append(guaranteeVisual);

        var amortizationVisual = $("<div>Amortization left" + (this. amortizationPeriod - this.yearsOld) + " years</div>");
        amortizationVisual.addClass("amortization-visualisation");
        container.append(amortizationVisual);

        return container;
    }
});

var Server = Class.create(Machine, {
    initialize: function ($super, years, guarantee, amortizationPeriod, mileage, OS, usage) {
        $super(years, guarantee, amortizationPeriod);
        this.mileage = mileage;
        this.leasing = OS;
        this.usage = usage;
    },

    renderPartial: function () {
        var container = $("<div>" + this.name + "</div>");
        container.addClass("server");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("server-full");

        var numberCores = $("<div>Number of cores: " + this.mileage + "</div>");
        numberCores.addClass("cores-visualisation");
        container.append(numberCores);
        
        var opSystem = $("<div>OS: " + this.leasing + "</div>");
        opSystem.addClass("os-visualisation");
        container.append(opSystem);
        
        var purpose = $("<div>Used for: " + this.usage + "</div>");
        purpose.addClass("usage-visualisation");
        container.append(purpose);
        
        return container;
    }
});

var Vehicle = Class.create(Machine, {
    initialize: function ($super, years, guarantee, amortizationPeriod, mileage, leasing, typeOfVehicle) {
        $super(years, guarantee, amortizationPeriod);
        this.mileage = mileage;
        this.leasing = leasing;
        this.typeOfVehicle = typeOfVehicle;
    },

    renderPartial: function () {
        var container = $("<div>" + this.name + "</div>");
        container.addClass("vehicle");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        return container;
    },

    renderFull: function ($super) {
        var container = $super();
        container.addClass("vehicle-full");

        var mileage = $("<div>Mileage: " + this.mileage + "per 100km</div>");
        mileage.addClass("mileage-visualisation");
        container.append(mileage);

        var leasing = $("<div>Leasing: " + this.leasing + "</div>");
        leasing.addClass("leasing-visualisation");
        container.append(leasing);

        var typeOfVehicle = $("<div>Type of vehicle: " + this.typeOfVehicle + "</div>");
        typeOfVehicle.addClass("typeOfVehicle-visualisation");
        container.append(typeOfVehicle);

        return container;
    }
});

var Branch = Class.create({
    initialize: function (town, numberOfPotentialClients) {
        this.town = town;
        this.numberOfPotentialClients = numberOfPotentialClients;
        this.buildings = [];
    },

    numberOfWorkers: function () {
        var counter = 0;
        for (var i = 0, len=this.buildings.length; i < len; i++) {
            counter = counter + this.buildings[i].workers.length;
        }

        return counter;
    },

    numberOfMachines: function () {
        var counter = 0;
        for (var i = 0, len = this.buildings.length; i < len; i++) {
            if (this.buildings[i].machines){
                counter = counter + this.buildings[i].machines.length;
            }
        }

        return counter;
    },

    addBuilding: function (building) {
        if (!(building instanceof Building)) {
            throw new Error("Only buildings can be added to branches.");
        }

        //check if building with the same parameters is not added already
        for (var i = this.buildings.length - 1; i >= 0; i--) {
            this.buildings[i]==building;
                return;
        };

        this.buildings.push(building);
        if (this.container) {
            if (this.container.children("ul.list-of-buildings").length > 0) {
                $(this.container).children("ul.list-of-buildings").first().append(building.renderPartial());
            }
            else {
                var buildingsList = $("<ul></ul>");
                buildingsList.addClass("list-of-buildings");
                for (var i = 0, len = this.buildings.length; i < len; i++) {
                    var listItem = this.buildings[i].renderPartial();
                    buildingsList.append(listItem);
                }

                buildingsList.sortable();
                $(this.container).append(buildingsList);
            }
        }

        if (this.fullContainer) {
            if ($(this.fullContainer).parent().length > 0) {
                $(this.fullContainer).children(".number-container-buildings").first().html("Number of buildings: " + this.buildings.length);
                $(this.fullContainer).children(".number-container-workers").first().html("Number of workers: " + this.numberOfWorkers());
                $(this.fullContainer).children(".number-container-machines").first().html("Number of machines: " + this.numberOfMachines());
            }
        }
    },

    renderPartial: function () {
        var container = $("<div></div>");
        container.addClass("branch");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        var branchName = $("<div>Branch: " + this.town + "</div>");
        branchName.addClass("branchName");
        container.append(branchName);

        if (this.buildings.length > 0) {
            var buildingsList = $("<ul></ul>");
            buildingsList.addClass("list-of-buildings");
            for (var i = 0, len = this.buildings.length; i < len; i++) {
                var listItem = this.buildings[i].renderPartial();
                buildingsList.append(listItem);
            }

            buildingsList.sortable();
            container.append(buildingsList);
        }

        this.container = container;
        return container;
    },

    renderFull: function () {
        var container = $("<div></div>");
        container.addClass("branch-full");

        var branchName = $("<div>Branch town: " + this.town + "</div>");
        branchName.addClass("branch-name");
        container.append(branchName);

        var customers = $("<div>Potential clients: " + this.numberOfPotentialClients + "</div>");
        container.append(customers);

        var buildings = $("<div>Number of buildings: " + this.buildings.length + "</div>");
        buildings.addClass("number-container-buildings");
        container.append(buildings);

        var numberOfWorkers = $("<div>Number of workers:" + this.numberOfWorkers() + "</div>");
        numberOfWorkers.addClass("number-container-workers");
        container.append(numberOfWorkers);

        var numberOfMachines = $("<div>Number of machines:" + this.numberOfMachines() + "</div>");
        numberOfMachines.addClass("number-container-machines");
        container.append(numberOfMachines);

        this.fullContainer = container;
        return container;
    }
});

var Company = Class.create({
    initialize: function (name, value) {
        this.name = name;
        this.value = value;
        this.branches = [];
    },

    numberOfWorkers: function () {
        var counter = 0;
        for (var i = 0, len = this.branches.length; i < len; i++) {
            counter = counter + this.branches[i].numberOfWorkers();
        }

        return counter;
    },

    numberOfMachines: function () {
        var counter = 0;
        for (var i = 0, len = this.branches.length; i < len; i++) {
            counter = counter + this.branches[i].numberOfMachines();
        }

        return counter;
    },

    addBranch: function (branch) {
        if (!(branch instanceof Branch)) {
            throw new Error("Only branches can be added to companies.");
        }

        this.branches.push(branch);
        if (this.container) {
            if (this.container.children("ul.list-of-branches").length > 0) {
                $(this.container).children("ul.list-of-branches").first().append(branch.renderPartial());
            }
            else {
                var branchesList = $("<ul></ul>");
                branchesList.addClass("list-of-branches");
                for (var i = 0, len = this.branches.length; i < len; i++) {
                    var listItem = this.branches[i].renderPartial();
                    branchesList.append(listItem);
                }

                branchesList.sortable();
                $(this.container).append(branchesList);
            }
        }

        if (this.fullContainer) {
            if ($(this.fullContainer).parent().length > 0) {
                $(this.fullContainer).children(".number-container-branches").first().html("Number of branches: " + this.branches.length);
                $(this.fullContainer).children(".number-container-workers").first().html("Number of workers: " + this.numberOfWorkers());
                $(this.fullContainer).children(".number-container-machines").first().html("Number of machines: " + this.numberOfMachines());
            }
        }
    },

    renderPartial: function () {
        var container = $("<div></div>");
        container.addClass("company");
        var self = this;
        container.on("click", function (event) {
            event.stopPropagation();
            if ($("#container-selected").length == 0) {
                var selectedContainer = $("<div></div>");
                selectedContainer.attr("id", "container-selected");
                $(document.body).append(selectedContainer);

                var previousButton = $("<button>Previous</button>");
                previousButton.attr("id", "prev-button");
                previousButton.on("click", localStorageControl.previous);
                $(document.body).append(previousButton);

                var nextButton = $("<button>Next</button>");
                nextButton.attr("id", "next-button");
                nextButton.on("click", localStorageControl.next);
                $(document.body).append(nextButton);
            }

            var container = $("#container-selected").first();
            container.html("");
            container.append(self.renderFull());
            localStorageControl.add();
        });

        var companyName = $("<div>Company: " + this.name + "</div>");
        companyName.addClass("companyName");
        container.append(companyName);

        if (this.branches.length > 0) {
            var branchesList = $("<ul></ul>");
            branchesList.addClass("list-of-branches");
            for (var i = 0, len = this.branches.length; i < len; i++) {
                var listItem = this.branches[i].renderPartial();
                branchesList.append(listItem);
            }

            branchesList.sortable();
            container.append(branchesList);
        }

        this.container = container;
        return container;
    },

    renderFull: function () {
        var container = $("<div></div>");
        container.addClass("company-full");

        var companyName = $("<div>Company: " + this.name + "</div>");
        companyName.addClass("company-name");
        container.append(companyName);

        var value = $("<div>Market value: " + this.value + "</div>");
        container.append(value);

        var branches = $("<div>Number of branches: " + this.branches.length + "</div>");
        branches.addClass("number-container-branches");
        container.append(branches);

        var numberOfWorkers = $("<div>Number of workers:" + this.numberOfWorkers() + "</div>");
        numberOfWorkers.addClass("number-container-workers");
        container.append(numberOfWorkers);

        var numberOfMachines = $("<div>Number of machines:" + this.numberOfMachines() + "</div>");
        numberOfMachines.addClass("number-container-machines");
        container.append(numberOfMachines);

        this.fullContainer = container;
        return container;
    }
});

//Moved to classes-demo.js





